package com.shengde.jinwawaforleader.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.views.MaskView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/** 
 * Android手指拍照  
 */  
@SuppressWarnings("deprecation")
public class CameraActivity extends Activity implements OnClickListener{  
	private View layout;  
    private Camera camera;  
    private Camera.Parameters parameters = null;  
    Bundle bundle = null; // 声明一个Bundle对象，用来存储数据  
    private Button cancelBtn;
    private Button confirmBtn;
    private Button cameraBtn;
    private Button cameraSelfBtn;
    private String filePath = "";
    private ImageView iv;
    private boolean hasClickCamera = false;
    private SurfaceView surfaceView;
    private static int degree;
    private boolean isBehind = true;
    private SurfaceHolder sufaceHolder;
    private boolean isNeedCut;
    private RelativeLayout cutLayout;
    private boolean isCanChange = false;
    
    private Bitmap resizedBitmap;
    private Bitmap orgBitmap;
    private int sw;
    private int sh;
    private MaskView maskView;
    @SuppressWarnings("deprecation")
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
   	@SuppressLint("NewApi")
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 显示界面  
        setContentView(R.layout.camera_activity);
        
        isNeedCut = getIntent().getBooleanExtra("needCut", false);
        layout = this.findViewById(R.id.buttonLayout);  
        cancelBtn = (Button) findViewById(R.id.cancelbtn);
        confirmBtn = (Button) findViewById(R.id.confirmbtn);
        cameraBtn = (Button) findViewById(R.id.takepicture);
        cameraSelfBtn = (Button) findViewById(R.id.changebtn);
        cameraSelfBtn.setVisibility(View.GONE);
//        cameraSelfBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
        cutLayout = (RelativeLayout) findViewById(R.id.camera_layout);
        iv = (ImageView) findViewById(R.id.scalePic);
//        LayoutParams params = new LayoutParams(800, 800);
      
        MulitPointTouchListener touchListener = new MulitPointTouchListener(iv);
        iv.setOnTouchListener(touchListener);
//        if(isNeedCut){
//        	touchListener.setCanZoom(true);
//        iv.setScaleType(ScaleType.CENTER_INSIDE);
//        }else{
//        	//iv.setScaleType(ScaleType.CENTER);
//        	iv.setScaleType(ScaleType.CENTER_INSIDE);
//        }
        surfaceView = (SurfaceView) this  
                .findViewById(R.id.surfaceView);  
        sufaceHolder = surfaceView.getHolder();
        surfaceView.getHolder()  
                .setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
        sw = getResources().getDisplayMetrics().widthPixels;
        sh = getResources().getDisplayMetrics().heightPixels;

        surfaceView.getHolder().setFixedSize(176, 144); //176, 144设置Surface分辨率  
        surfaceView.getHolder().setKeepScreenOn(true);// 屏幕常亮  
        surfaceView.getHolder().addCallback(new SurfaceCallback());//为SurfaceView的句柄添加一个回调函数 
        
        cameraSelfBtn.setVisibility(View.GONE);
        
        maskView = (MaskView) findViewById(R.id.maskView);
        Rect screenCenterRect = createCenterScreenRect();
		maskView.setCenterRect(screenCenterRect);
//		maskView.setVisibility(View.GONE);
//        if (Build.VERSION.SDK_INT >=9) { 
//        	if(Camera.getNumberOfCameras() > 1){
//       			isCanChange = true;
//       			cameraSelfBtn.setVisibility(View.GONE);
//       		}
//        }
    }  
    /** 
     * 按钮被点击触发的事件 
     *  
     * @param v 
     */  
    @SuppressWarnings("deprecation")
	public void btnOnclick(View v) {  
        if (camera != null) {  
            switch (v.getId()) {  
            case R.id.takepicture: 
            	hasClickCamera = true;
                // 拍照  
                camera.takePicture(null, null, new MyPictureCallback());  
                break;  
            }  
        }  
    }    
  
    @SuppressWarnings("deprecation")
	private final class MyPictureCallback implements PictureCallback {  
  
        @SuppressLint("NewApi")
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override  
		public void onPictureTaken(byte[] data, Camera camera) {
			try {
				bundle = new Bundle();
				bundle.putByteArray("bytes", data); // 将图片字节数据保存在bundle当中，实现数据交换
				saveToSDCard(data); // 保存图片到sd卡中
				// camera.startPreview(); // 拍完照后，重新开始预览
				if (!TextUtils.isEmpty(filePath)) {
					surfaceView.setVisibility(View.GONE);
					maskView.setVisibility(View.GONE);
					iv.setVisibility(View.VISIBLE);
					if (isNeedCut) {
						cutLayout.setVisibility(View.VISIBLE);
					}
					// Bitmap bitmap = BitmapFactory.decodeFile(filePath);
					orgBitmap = BitmapFactory.decodeFile(filePath);
					if (null != orgBitmap) {
						 iv.setImageBitmap(rotaingImageView(degree, filePath));
						 int x = (int)(DisplayUtil.getScreenMetrics(CameraActivity.this).x * 0.8);
						 int y = (int)(DisplayUtil.getScreenMetrics(CameraActivity.this).y * 0.7);
						 iv.setLayoutParams(new LayoutParams(x, y));
						confirmBtn.setVisibility(View.VISIBLE);
						cameraBtn.setVisibility(View.GONE);
						cameraSelfBtn.setVisibility(View.GONE);

					}
				} else {
					Toast.makeText(CameraActivity.this, "扩展存储设备未安装",Toast.LENGTH_LONG);
					finish();
				}
			} catch (Exception e) {
				Toast.makeText(CameraActivity.this, "扩展存储设备未安装",Toast.LENGTH_LONG);
				finish();
			}
		}  
    }  
  
    /** 
     * 将拍下来的照片存放在SD卡中 
     * @param data   
     * @throws IOException 
     */  
    public  void saveToSDCard(byte[] data) throws IOException {  
        Date date = new Date();  
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间  
        String filename = format.format(date) + ".jpg";  
        filePath = StorageUtils.YR_CAMERA_DIR +filename;
        File fileFolder = new File(StorageUtils.YR_CAMERA_DIR);
        if (!fileFolder.exists()) { 
            fileFolder.mkdir();  
        }  
        File jpgFile = new File(fileFolder, filename);  
        FileOutputStream outputStream = new FileOutputStream(filePath); // 文件输出流  
        outputStream.write(data); // 写入sd卡中  
        outputStream.close(); // 关闭输出流  
    }  
  
  
    private final class SurfaceCallback implements Callback {

    	// 拍照状态变化时调用该方法  
        @SuppressWarnings("deprecation")
		@Override  
        public void surfaceChanged(SurfaceHolder holder, int format, int width,  
                int height) {  
         	if (camera == null ||camera.getParameters()==null) {
        		finish();
        	  Toast.makeText(CameraActivity.this, "金娃娃-园长版已被禁止权限：调用摄像头。可在手机管家-权限管理重新授权。", 1).show();
            	//return;
			} else {
				    parameters = camera.getParameters(); // 获取各项参数  
		            parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式  
		            //parameters.setPreviewSize(width, height); // 设置预览大小  
		            parameters.setPreviewFrameRate(5);  //设置每秒显示4帧  
		            parameters.setPictureSize(width, height); // 设置保存的图片尺寸  
		            parameters.setJpegQuality(90); // 设置照片质量  
		            try {
						camera.setPreviewDisplay(holder);
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
          
           

        }  
  
        // 开始拍照时调用该方法  
        @SuppressWarnings("deprecation")
		@Override  
        public void surfaceCreated(SurfaceHolder holder) {  
        	isBehind = true;
            try {  
                camera = Camera.open(); // 打开摄像头  
                camera.setPreviewDisplay(sufaceHolder); // 设置用于显示拍照影像的SurfaceHolder对象  
                camera.setDisplayOrientation(getPreviewDegree(CameraActivity.this));  
                Camera.Parameters myParam = camera.getParameters();
		        myParam.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);  
		        List<Size> list = myParam.getSupportedPictureSizes();
		        Collections.sort(list, new Comparator<Size>() {
		        	  public int compare(final Size a, final Size b) {
		        	    return  b.width * b.height - a.width * a.height;
		        	  }
		        	});
		        
		        if (list.size() > 4) {
		        	myParam.setPictureSize(list.get(2).width, list.get(2).height);
		        }else {
		        	myParam.setPictureSize(list.get(0).width, list.get(0).height);
		        }
				
		        camera.setParameters(myParam);
		        maskView.setVisibility(View.VISIBLE);
		        //camera.autoFocus(null);
                camera.startPreview(); // 开始预览  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
  
        }  
  
        // 停止拍照时调用该方法  
        @Override  
        public void surfaceDestroyed(SurfaceHolder holder) {  
            if (camera != null) {  
                camera.release(); // 释放照相机  
                camera = null;  
            }  
        }  
    }  
    @SuppressWarnings("deprecation")
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
   	@SuppressLint("NewApi")
   	public void changeCamera(boolean behind){
    	CameraInfo cameraInfo = new CameraInfo();
   		int cameraCount = Camera.getNumberOfCameras();
    	if(cameraCount <= 1){
    		return;
    	}
    	if(null != camera){
    		camera.release();
    		camera = null;
    	}
   		for (int id = 0; id < cameraCount; id++) {
   			Camera.getCameraInfo(id, cameraInfo);
   			if(cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT && behind){//CAMERA_FACING_BACK后置摄像头
   				isBehind = false;
   				camera = Camera.open(id);
   				try {
   					camera.setPreviewDisplay(sufaceHolder);
   					camera.setDisplayOrientation(getPreviewDegree(CameraActivity.this));  
   					//camera.autoFocus(null);
   		         	camera.startPreview();

   					break;
   				} catch (IOException e) {
   					e.printStackTrace();
   				} 
   			}
   			if(cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK && !behind){
   				isBehind = true;
   				camera = Camera.open(id);
   				try {
   					camera.setPreviewDisplay(sufaceHolder);
   					camera.setDisplayOrientation(getPreviewDegree(CameraActivity.this));  
   					Camera.Parameters myParam = camera.getParameters();
   		            myParam.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);  
   		            camera.setParameters(myParam);
   		            //camera.autoFocus(null);
   		         	camera.startPreview();

   					break;
   				} catch (IOException e) {
   					e.printStackTrace();
   				}
   			}
   		}
       }
    /** 
     * 点击手机屏幕是，显示两个按钮 
     */  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        switch (event.getAction()) {  
        case MotionEvent.ACTION_DOWN:  
            layout.setVisibility(ViewGroup.VISIBLE); // 设置视图可见  
            break;  
        }  
        return true;  
    }  
       /**
        * 旋转图片
        * @param angle
        * @param bitmap
        * @return Bitmap
        */ 
       public Bitmap rotaingImageView(int angle, String filePath) { 
    	   Matrix matrix = new Matrix();
			if (!isBehind) {
				//angle = 270;
				matrix.postRotate(angle);
				matrix.postScale(1, -1);
			} else {
				matrix.postRotate(angle);
			}
			
			long timet1 = System.currentTimeMillis();
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			newOpts.inSampleSize = 8;
	        Bitmap bitmap = BitmapFactory.decodeFile(filePath, newOpts);//此时返回bm为空      
	        Bitmap resizedBitmap = null;
	        int x = (int)(bitmap.getWidth() * 0.15);
	        int y = (int)(bitmap.getHeight() * 0.1);
	        int w = (int)(bitmap.getWidth() * 0.7);
	        int h = (int)(bitmap.getHeight() * 0.8);
			resizedBitmap = Bitmap.createBitmap(bitmap, x, y, w, h, matrix, true);
			byte[] data = compressImage(resizedBitmap);
			FileOutputStream outputStream = null;
			try {
				outputStream = new FileOutputStream(filePath, false);
				outputStream.write(data);
				outputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

			if(null != bitmap && !bitmap.isRecycled()){
				bitmap.recycle();
				bitmap = null;
			}
			return BitmapFactory.decodeFile(filePath);
       }
       

       private byte[] compressImage(Bitmap image) {  
           ByteArrayOutputStream baos = new ByteArrayOutputStream();  
           image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  
           int options = 100;  
           while ( baos.toByteArray().length / 1024 > 1000) {  //循环判断如果压缩后图片是否大于200kb,大于继续压缩         
               baos.reset();//重置baos即清空baos  
               image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中  
               options -= 10;//每次都减少10  
           }  
           if(null != image && !image.isRecycled()){
        	   image.recycle();
        	   image = null;
           }
           return baos.toByteArray();  
       }
       
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        switch (keyCode) {  
        case KeyEvent.KEYCODE_CAMERA: // 按下拍照按钮  
            if (camera != null && event.getRepeatCount() == 0) {  
                // 拍照  
                //注：调用takePicture()方法进行拍照是传入了一个PictureCallback对象——当程序获取了拍照所得的图片数据之后  
                //，PictureCallback对象将会被回调，该对象可以负责对相片进行保存或传入网络  
                camera.takePicture(null, null, new MyPictureCallback());  
            }  
        }  
        return super.onKeyDown(keyCode, event);  
    }  
    // 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度  
    public int getPreviewDegree(Activity activity) {  
        // 获得手机的方向  
        int rotation = activity.getWindowManager().getDefaultDisplay()  
                .getRotation();  
        degree = 0;  
        // 根据手机的方向计算相机预览画面应该选择的角度  
        switch (rotation) {  
        case Surface.ROTATION_0:
        	degree = 90;
            break;  
        case Surface.ROTATION_90:
        	if(isBehind){
        		degree = 0;
            }else{
            	degree = 180;
            }
            break;  
        case Surface.ROTATION_180:
        	if(isBehind){
        		degree = 270;  
        	}else{
        		degree = 90;
        	}
            break;  
        case Surface.ROTATION_270:  
            if(isBehind){            	
            	degree = 180;  
            }else{
            	degree = 0;
            }
            break;  
        }  
        return degree;  
    }

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.cancelbtn:
			if(hasClickCamera){
				iv.setVisibility(View.GONE);
				cutLayout.setVisibility(View.GONE);
				confirmBtn.setVisibility(View.GONE);
				cameraBtn.setVisibility(View.VISIBLE);
				iv.setImageBitmap(null);
				surfaceView.setVisibility(View.VISIBLE);
				hasClickCamera = false;
				if(isCanChange){					
					cameraSelfBtn.setVisibility(View.GONE);
				}
				if(null != orgBitmap && !orgBitmap.isRecycled()){
					orgBitmap.recycle();
					orgBitmap = null;
				}
                camera.startPreview(); // 开始预览
                return;
			}
			finish();
			break;
		case R.id.confirmbtn:
			Intent intent = new Intent();
	        intent.putExtra("path", filePath);
	        setResult(RESULT_OK, intent);
	        CameraActivity.this.finish();
			break;
		case R.id.changebtn:
//			Animation animation=AnimationUtils.loadAnimation(CameraActivity.this, R.anim.overturn);
//			cameraSelfBtn.startAnimation(animation);
//			if(null != orgBitmap && !orgBitmap.isRecycled()){
//				orgBitmap.recycle();
//				orgBitmap = null;
//			}
//			iv.setImageBitmap(null);
//			changeCamera(isBehind);
			break;
			default:
				break;
		}
	}
	public void saveMyBitmap(Bitmap mBitmap){
		Date date = new Date();  
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间  
        String filename = "avatar"+format.format(date) + ".png";  
        filePath = StorageUtils.YR_CAMERA_DIR +filename;
		File tempFile = new File(filePath);
		FileOutputStream fOut = null;
		try {
			if (tempFile.exists()) {
				tempFile.delete();
			}
			tempFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	  try {
		  fOut = new FileOutputStream(tempFile);
	  } catch (FileNotFoundException e) {
		  e.printStackTrace();
	  }
		try {
			mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			if (fOut != null) {
				fOut.flush();
				fOut.close();
			}
		} catch (IOException e) {
		  e.printStackTrace();
	  }
	  if(null != mBitmap && !mBitmap.isRecycled()){
		  mBitmap.recycle();
		  mBitmap = null;
	  }
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != resizedBitmap && !resizedBitmap.isRecycled()){
			resizedBitmap.recycle();
			resizedBitmap = null;
			System.gc();
		}
		if(null != orgBitmap && !orgBitmap.isRecycled()){
			orgBitmap.recycle();
			orgBitmap = null;
		}
	}
	
	private Rect createCenterScreenRect(){
		int x1 = (int)(DisplayUtil.getScreenMetrics(this).x * 0.1);
		int y1 = (int)(DisplayUtil.getScreenMetrics(this).y * 0.15);
		int x2 = (int)(DisplayUtil.getScreenMetrics(this).x * 0.9);
		int y2 = (int)(DisplayUtil.getScreenMetrics(this).y * 0.85);
		return new Rect(x1, y1, x2, y2);
	}
}